//
//  ZLAntiShakeSwitchDemo.m
//  PersonalOCTest
//
//  ZLAntiShakeSwitch 使用示例
//

#import "ZLAntiShakeSwitchDemo.h"
#import "ZLAntiShakeSwitch.h"

@interface ZLAntiShakeSwitchDemo () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *switchTitles;
@property (nonatomic, strong) NSMutableArray *switchStates;

@end

@implementation ZLAntiShakeSwitchDemo

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupData];
    [self setupUI];
}

- (void)setupData {
    self.title = @"防呆开关示例";
    
    // 模拟多个开关的标题
    self.switchTitles = @[
        @"消息推送",
        @"声音提醒", 
        @"震动反馈",
        @"勿扰模式",
        @"夜间模式",
        @"自动锁屏",
        @"省电模式",
        @"蓝牙连接"
    ];
    
    // 初始化开关状态
    self.switchStates = [NSMutableArray array];
    for (NSInteger i = 0; i < self.switchTitles.count; i++) {
        [self.switchStates addObject:@(i % 2 == 0)]; // 交替设置初始状态
    }
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    
    // 创建TableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor systemGroupedBackgroundColor];
    [self.view addSubview:self.tableView];
    
    // 添加重置按钮
    UIBarButtonItem *resetButton = [[UIBarButtonItem alloc] initWithTitle:@"重置防呆" style:UIBarButtonItemStylePlain target:self action:@selector(resetAntiShake)];
    self.navigationItem.rightBarButtonItem = resetButton;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2; // 分为两个区域展示
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4; // 前4个开关
    } else {
        return self.switchTitles.count - 4; // 后4个开关
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"SwitchCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    // 计算实际的索引
    NSInteger actualIndex = indexPath.section == 0 ? indexPath.row : (indexPath.row + 4);
    
    // 配置cell内容
    cell.textLabel.text = self.switchTitles[actualIndex];
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    
    // 创建防呆开关
    ZLAntiShakeSwitch *antiShakeSwitch = [ZLAntiShakeSwitch switchWithIdentifier:[NSString stringWithFormat:@"switch_%ld", (long)actualIndex]];
    antiShakeSwitch.on = [self.switchStates[actualIndex] boolValue];
    antiShakeSwitch.antiShakeInterval = 1.0; // 1秒防呆间隔
    antiShakeSwitch.enableGlobalMutex = YES; // 启用全局互斥
    
    // 设置开关状态变化回调
    __weak typeof(self) weakSelf = self;
    [antiShakeSwitch setValueChangedBlock:^(ZLAntiShakeSwitch *antiShakeSwitch, BOOL isOn) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf handleSwitchValueChanged:antiShakeSwitch isOn:isOn atIndex:actualIndex];
        }
    }];
    
    cell.accessoryView = antiShakeSwitch;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"基础设置";
    } else {
        return @"高级设置";
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return @"每个开关1秒内只能点击一次，防止误操作";
    } else {
        return @"任意开关点击后，其他开关需等待1秒才能操作";
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0;
}

#pragma mark - 事件处理

- (void)handleSwitchValueChanged:(ZLAntiShakeSwitch *)antiShakeSwitch isOn:(BOOL)isOn atIndex:(NSInteger)index {
    // 更新数据源
    self.switchStates[index] = @(isOn);
    
    // 打印日志，便于调试
    NSLog(@"开关 '%@' (ID: %@) 状态变更为: %@", 
          self.switchTitles[index], 
          antiShakeSwitch.switchIdentifier, 
          isOn ? @"开启" : @"关闭");
    
    // 这里可以添加具体的业务逻辑
    [self performBusinessLogicForSwitchAtIndex:index isOn:isOn];
}

- (void)performBusinessLogicForSwitchAtIndex:(NSInteger)index isOn:(BOOL)isOn {
    // 模拟不同开关的业务逻辑
    NSString *switchName = self.switchTitles[index];
    
    if ([switchName isEqualToString:@"消息推送"]) {
        // 处理消息推送逻辑
        NSLog(@"消息推送已%@", isOn ? @"开启" : @"关闭");
    } else if ([switchName isEqualToString:@"勿扰模式"]) {
        // 处理勿扰模式逻辑
        NSLog(@"勿扰模式已%@", isOn ? @"开启" : @"关闭");
        if (isOn) {
            // 勿扰模式开启时，可能需要关闭其他相关功能
            [self showAlert:@"勿扰模式已开启，将暂停部分通知功能"];
        }
    }
    // 其他开关的业务逻辑...
}

- (void)resetAntiShake {
    // 重置所有开关的防呆状态
    [ZLAntiShakeSwitch resetAllAntiShakeStates];
    [self showAlert:@"已重置所有开关的防呆状态"];
}

- (void)showAlert:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" 
                                                                   message:message 
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" 
                                                       style:UIAlertActionStyleDefault 
                                                     handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 内存管理

- (void)dealloc {
    NSLog(@"ZLAntiShakeSwitchDemo dealloc");
}

@end